<!-- src/components/StudentData.vue -->
<template>
  <div>


    <div class="search-and-export">
      <el-input placeholder="请输入姓名" v-model="searchName" class="input-with-select">
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <el-button type="primary" @click="exportExcel">Export</el-button>
    </div>

    <el-table :data="filteredStudents" style="width: 100%">
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="grade" label="年级" width="180"></el-table-column>
      <el-table-column prop="phone" label="电话" width="180"></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" @click="deleteStudent(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
import axios from 'axios';
import * as XLSX from 'xlsx';

export default {
  name: 'StudentData',
  data() {
    return {
      students: [],
      searchName: '',
      currentPage: 1,
      pageSize: 10,
      total: 0
    };
  },
  computed: {
    filteredStudents() {
      let filtered = this.students.filter(student => {
        return student.name.toLowerCase().includes(this.searchName.toLowerCase());
      });

      this.total = filtered.length;
      return filtered.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    }
  },
  created(){
    this.fetchStudentData()
  },

  methods: {
    fetchStudentData(){
      let courseId = this.$route.params.courseId //通过路由传递获取
      axios.get("/api/teacher/stus?courseId="+courseId).then(response => {
        this.students = response.data.map(student =>{
          switch(student.grade){
            case 1:
              student.grade = "大一"
              break
            case 2:
              student.grade = "大二"
              break
            case 3:
              student.grade = "大三"
              break
            case 4:
              studnet.grade = "大四"
              break
          }
          return student
        })
      }).catch(err => {
        this.$message.error(err.response.data)
      })
    },

    exportExcel() {
      const data = XLSX.utils.json_to_sheet(this.students);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, data, 'Students');
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      this.saveAsExcelFile(excelBuffer, 'students');
    },
    saveAsExcelFile(buffer, fileName) {
      const data = new Blob([buffer], { type: 'application/octet-stream' });
      const url = window.URL.createObjectURL(data);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `${fileName}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    deleteStudent(id) {
      //获取学生ID和课程ID
      let stuId = id
      let courseId = this.$route.params.courseId //通过路由传递获取
      axios.get("/api/teacher/deleteById",{params:{
        stuId,
        courseId
      }}).then(response => {
        this.$message.success("删除成功")
        this.fetchStudentData()

      }).catch(err => {
        this.$message.error("删除失败")
      })

      this.students = this.students.filter(student => student.id !== id);
    },

    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    }
  }
};
</script>

<style scoped>
.breadcrumb {
  margin-bottom: 20px;
}

.search-and-export {
  display: flex;
  margin-bottom: 20px;
}

.input-with-select {
  width: 300px;
  margin-right: 20px;
}

.el-pagination {
  margin-top: 20px;
}
</style>
